package cn.lzj.basic.interceptor;

import cn.lzj.basic.annotation.PreAuthorize;
import cn.lzj.basic.jwt.JwtUtils;
import cn.lzj.basic.jwt.LoginData;
import cn.lzj.basic.jwt.Payload;
import cn.lzj.basic.jwt.RsaUtils;
import cn.lzj.user.domain.Logininfo;
import cn.lzj.user.mapper.LogininfoMapper;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.配置；拦截器  获取token
        String token = request.getHeader("token");
        //3.有token，比较信息，通过token获取redis 的登录信息
        if (token != null) {

            PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
            try {
                Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                //logininfo
                if (payload != null) {//登录成功，没有过期

                    Logininfo logininfo = payload.getLoginData().getLogininfo();
                    //刷新过期时间
                    if (logininfo.getType() == 1) {
                        //1,是前端用户，直接放行
                        return true;
                    }
                    //2.校验权限登录成功，如果是后台用户--继续校验权限
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (preAuthorize == null) {
                        return true;
                    } else {

                        String sn = preAuthorize.sn();
                        //查询出当前登录人所拥有的所有权限：t_permission中的sn
                        List<String> ownPerssions = logininfoMapper.loadPerssionSnByLogininfoId(logininfo.getId());
                        //如果集合中包含所拥有的权限，就放行 --有sn字段信息
                        if (ownPerssions.contains(sn)) {
                            //contains是比较是否有这个信息
                            return true;
                        } else {
                            //如果没有，让他去找管理员
                            response.setCharacterEncoding("UTF-8");
                            response.setContentType("application/json;charset=UTF-8");
                            PrintWriter writer = response.getWriter();
                            writer.println("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.close();
                            return false;
                        }
                    }
                }
            } catch (ExpiredJwtException e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"timeout\"}");
                return false;
            }
        }
        //2.判断token  如果为null--直接拦截，响应到前端，跳转到登录页面
        //response.setCharacterEncoding("UTF-8");
        //后端响应一个json对象给前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
        //4.如果登录信息为空--过期，请重新登录，响应到前端，跳转到登录页面
        //5.如果登录信息不为null--放行，并且重新设置过期时间
        return false;
    }
}